﻿/*
 * This file is part of MonoStrategy.
 *
 * Copyright (C) 2010-2011 Christoph Husse
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors: 
 *      # Christoph Husse
 * 
 * Also checkout our homepage: http://monostrategy.codeplex.com/
 */
using System;
using System.Collections.Generic;
using System.Linq;

namespace MonoStrategy
{
    public static class CollectionExtensions
    {
        public static bool IsSet(this TerrainCellFlags value, TerrainCellFlags flag)
        {
            return ((value & flag) != 0);
        }

        public static int BitCount<TEnum>(this TEnum value) where TEnum : struct
        {
            if (typeof(TEnum).IsEnum)
            {
                return Convert.ToInt64(value).BitCount();
            }
            else if (typeof(TEnum).IsPrimitive)
            {
                long intVal = Convert.ToInt64(value);
                int result = 0;

                for (int i = 0; i < 64; i++)
                {
                    if ((intVal & (((long)1) << i)) != 0)
                        result++;
                }

                return result;
            }
            else
                throw new ArgumentException("TEnum must be an enumerative or integer type");
        }

        public static bool IsSet<TEnum>(this TEnum value, TEnum flag) where TEnum : struct
        {
            if (!typeof(TEnum).IsEnum)
                throw new ArgumentException("TEnum must be an enumerated type");

            long valueBase = Convert.ToInt64(value);
            long flagBase = Convert.ToInt64(flag);
            return (valueBase & flagBase) == flagBase;
        }

        public static String Padding(this String This, int inLength)
        {
            if (This.Length >= inLength)
                return This;

            return This + new String(' ', inLength - This.Length);
        }

        public static Int32 BinarySearch<T>(this IList<T> list, T value)
        {
            IComparer<T> Comparer = Comparer<T>.Default;

            return BinarySearch(list, value, Comparer<T>.Default);
        }

        public static Int32 BinarySearch<T>(this IList<T> list, T value, IComparer<T> comparer)
        {
            #region Parameter Validation

            if (Object.ReferenceEquals(null, list))
                throw new ArgumentNullException("list");
            if (Object.ReferenceEquals(null, comparer))
                throw new ArgumentNullException("comparer");

            #endregion

            return BinarySearch(list, value, 0, list.Count - 1, comparer);
        }

        private static Int32 BinarySearch<T>(IList<T> list, T value, Int32 low, Int32 high, IComparer<T> comparer)
        {

            if (high < low)
                return -1 - low; // not found

            Int32 mid = low + ((high - low) / 2);
            Int32 comp = comparer.Compare(list[mid], value);

            if (comp > 0)
                return BinarySearch(list, value, low, mid - 1, comparer);
            else if (comp < 0)
                return BinarySearch(list, value, mid + 1, high, comparer);
            else
                return mid; // found
        }  

        public static int IndexOf<T>(this IEnumerable<T> inThis, T inElement)
        {
            Int32 i = 0;

            foreach (var e in inThis)
            {
                if (e.Equals(inElement))
                    return i;

                i++;
            }

            return -1;
        }

        public static List<Int32[]> CreatePermutations(this Int32[] inThis)
        {
            List<Int32[]> result = new List<int[]>();
            Int32[] array = new Int32[inThis.Length];

            for (int i = 0; i < array.Length; i++)
            {
                array[i] = i;
            }

            GenSubPermutation(array, 0, result);

            return result;
        }

        private static void GenSubPermutation(Int32[] inBase, Int32 inIndex, List<Int32[]> inResult)
        {
            if (inIndex + 1 >= inBase.Length)
            {
                inResult.Add(inBase);

                return;
            }

            for (int i = inIndex + 1; i < inBase.Length; i++)
            {
                // swap "inIndex" with "i"
                Int32[] sub = inBase.ToArray<Int32>();

                sub[inIndex] = sub[i];
                sub[i] = inBase[inIndex];

                GenSubPermutation(sub, inIndex + 1, inResult);
            }

            GenSubPermutation(inBase.ToArray<Int32>(), inIndex + 1, inResult);
        }

        public static List<TValue> Permutate<TValue>(this List<TValue> inThis, IEnumerable<Int32> inPermutation) 
        {
            List<TValue> result = new List<TValue>();

            foreach(Int32 i in inPermutation)
            {
                result.Add(inThis[i]);
            }

            return result;
        }

        public static void Fill(this Int32[] inThis, Int32 inStartValue, Int32 inStride)
        {
            for (int i = 0, current = inStartValue; i < inThis.Length; i++, current += inStride)
            {
                inThis[i] = current;
            }
        }

        public static void Fill(this Int64[] inThis, Int32 inStartValue, Int32 inStride)
        {
            for (int i = 0, current = inStartValue; i < inThis.Length; i++, current += inStride)
            {
                inThis[i] = current;
            }
        }

        public static void Fill(this Double[] inThis, Int32 inStartValue, Int32 inStride)
        {
            for (int i = 0, current = inStartValue; i < inThis.Length; i++, current += inStride)
            {
                inThis[i] = current;
            }
        }

        public static Object[] ToObjects(this System.Collections.ICollection inCollection)
        {
            List<Object> result = new List<object>();
            System.Collections.IEnumerator enumerator = inCollection.GetEnumerator();

            while(enumerator.MoveNext())
            {
                result.Add(enumerator.Current);
            }

            return result.ToArray();
        }
    }
}
